package com.tvserials.notification.rest;

import com.tvserials.notification.dto.Episode;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.exceptions.NetworkConnectionException;
import com.tvserials.notification.exceptions.PageParseException;
import com.tvserials.notification.parser.PageParser;
import com.tvserials.notification.parser.PageParserFactory;
import com.tvserials.notification.vo.SourceType;
import com.tvserials.notification.vo.TvEpisodeFilterVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class NotificationsController {

    @RequestMapping(value = "/episodes", method = RequestMethod.POST)
    public List<Episode> getEpisodes(@RequestBody TvEpisodeFilterVO filterVO) throws NetworkConnectionException, PageParseException {
        List<Episode> episodes = new ArrayList<Episode>();
        for (SourceType sourceType : filterVO.getSourceTypes()) {
            PageParser pageParser = PageParserFactory.getPageParser(sourceType);
            try {
                episodes.addAll(pageParser.parsePage(filterVO));
            } catch (Exception e) {
                System.out.println("Failed to get data for " + sourceType);
            }
        }
        return episodes;
    }

    @RequestMapping(value = "/serials", method = RequestMethod.POST)
    public List<Serial> getSerials(@RequestBody SourceType sourceType) throws NetworkConnectionException, PageParseException {
        PageParser pageParser = PageParserFactory.getPageParser(sourceType);
        return pageParser.parseSerialsList();
    }
}
